package com.qspda.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;

import com.qs.utils.BarcodeCreater;
import com.qs.utils.PrintUtils;

import java.lang.reflect.Method;
import java.util.Locale;

import static com.qs.utils.PrintUtils.send;


/**
 * 特别注意事项：在进行接口集成之前，
 * 需要先把机器上出厂安装的测试APP卸掉，
 * 避免串口调用冲突，如不卸载，会出现扫描延迟、打印延迟甚至失败现象
 *
 * @author wusiliang
 * @time 2023年02月21日14:33:32
 */
public class MainActivity extends Activity implements TextToSpeech.OnInitListener {

    // 扫描信息接收广播
    private ScanBroadcastReceiver scanBroadcastReceiver;
    //打印结果接收广播
    private GetMessageBroadcastReceiver getMessageBroadcastReceiver;
    //扫描广播接收
    ScanBroadcastReceiver1 scanBroadcastReceiver1;
    //内容输入编辑框
    private EditText tv;
    //设备信息二维码
    private ImageView device_img;
    //普通热敏纸和间隙标签纸选择
    private RadioGroup rg, paper_height,paper_width,paper_text_size,paper_align,paper_top;
    // 提示音
    private MediaPlayer player;

    int paperHeight = 30;

    int paperWidth=52;

    int paperTextSize=3;

    int paperAlign=1;

    int paperTop=2;

    boolean printComplete = true;

    //tts语音
    private TextToSpeech textToSpeech;

    private SharedPreferences sharedPreferences = null;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sharedPreferences = getSharedPreferences("printer", MODE_PRIVATE);

        try {
            //初始化打印工具
            PrintUtils.initPrintUtils(this);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    // 关闭标签检测指令，即关闭黑标功能，true为开启，false为关闭
                    PrintUtils.labelEnable(false);
                    //黑标起始位设置，默认为52
                    PrintUtils.setStarNum(52);

                    //初始化打印机
                    send(new byte[]{0x1b, 0x40});

                }
            }, 2500);
        } catch (Throwable e) {
            e.printStackTrace();
            Toast.makeText(this, "非法设备" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        // 实例化MediaPlayer
        player = MediaPlayer.create(getApplicationContext(), R.raw.beep);

        //控件初始化
        tv = (EditText) findViewById(R.id.tv);

        rg = (RadioGroup) findViewById(R.id.rg);
        paper_height = (RadioGroup) findViewById(R.id.paper_height);
        paper_text_size = (RadioGroup) findViewById(R.id.paper_text_size);
        paper_align = (RadioGroup) findViewById(R.id.paper_align);
        paper_top = (RadioGroup) findViewById(R.id.paper_top);

        paper_width =findViewById(R.id.paper_width);

        device_img = findViewById(R.id.device_img);

        tv.setText("打印测试1234567890");

        /**
         * 打印文字
         */
        findViewById(R.id.btn_printText).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        String str = tv.getText().toString();

                        /**
                         * 打印文字
                         *
                         * @param paper_width
                         *        纸张宽度选择，目前只有30mm、40mm和52mm可选
                         * @param size
                         *       文字大小，其中1为正常字体，2为双倍宽高字体，暂不支持其他字体大小
                         * @param align
                         *       对齐方式，其中0为居左，1为居中，2为居右
                         * @param top
                         *       对齐方式，其中0、1为居上，2为居中，3为居下
                         * @param text
                         *       要打印的文字
                         * @param isLabel
                         *       是否进行标签走纸，设为true时候打印完自动走纸到下一页，只有开启标签/黑标功能时有效
                         * @param tearPape
                         *       打印完是否要撕纸，设为true时候会打印完多走3空行，把纸张推出来，方便撕纸操作,只有关闭标签/黑标功能时有效
                         */
                        PrintUtils.printText(paperWidth,paperTextSize, paperAlign, paperTop, str, true,true);
                    }
                });

        /**
         * 打印一维码
         */
        findViewById(R.id.btn_printBarcode).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        String barStr = tv.getText().toString();
                        if ( barStr.length() <= 0||barStr.length()>30){
                            Toast.makeText(MainActivity.this, "当前数据不能生成一维码",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        // 判断当前字符能否生成条码
                        if (barStr.getBytes().length > barStr.length()) {
                            Toast.makeText(MainActivity.this, "当前数据不能生成一维码",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        /**
                         * 打印一维码
                         * @param align 对齐方式，其中0为居左，1为居中，2为居右
                         * @param top 对齐方式，对齐方式，其中0、1为居上，2为居中，3为居下
                         * @param width 打印一维码宽度，由于纸张限制，58纸张最大打印宽度为384，80纸张最大打印宽度为570，超过则可能无法打印
                         * @param height 打印一维码的高度
                         * @param data 一维码的内容（不能是中文，否则会报错）
                         * @param isShowBarStr  是否显示条码内容
                         * @param size  条码内容文字大小，单位是sp
                         * @param isLabel 是否进行标签走纸，设为true时候打印完自动走纸到下一页，只有开启标签/黑标功能时有效
                         * @param tearPape  打印完是否要撕纸，设为true时候会打印完多走3空行，把纸张推出来，方便撕纸操作,只有关闭标签/黑标功能时有效
                         */
                        if (paperHeight == 30) {
                            PrintUtils.printBarCode(paperWidth,paperAlign,paperTop, 200, 100, barStr, true, 30 , true,true);
                        } else {
                            PrintUtils.printBarCode(paperWidth,paperAlign,paperTop, 250, 120, barStr, true, 30 , true,true);
                        }
                    }
                });

        /**
         * 打印二维码
         */
        findViewById(R.id.btn_printQRcode).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        // TODO Auto-generated method stub
                        final String qrStr = tv.getText().toString();
                        if (qrStr.length() <= 0) {
                            Toast.makeText(MainActivity.this, "当前数据不能为空",
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        /**
                         * 打印二维码
                         * @param align 对齐方式，0 左对齐，1 居中，2右对齐
                         * @param top 对齐方式，对齐方式，其中0、1为居上，2为居中，3为居下
                         * @param width 二维码宽度
                         * @param height 二维码高度
                         * @param data 二维码内容
                         * @param isShowQRStr 是否显示二维码内容
                         * @param size 二维码内容大小
                         * @param isLabel 是否进行标签走纸，设为true时候打印完自动走纸到下一页，只有开启标签/黑标功能时有效
                         * @param tearPape  打印完是否要撕纸，设为true时候会打印完多走3空行，把纸张推出来，方便撕纸操作,只有关闭标签/黑标功能时有效
                         */

                        if (paperHeight == 30) {
                            PrintUtils.printQRCode(paperWidth,paperAlign,paperTop, 160, 160, qrStr, false, 30 , true,true);
                        } else {
                            PrintUtils.printQRCode(paperWidth,paperAlign,paperTop, 210, 210, qrStr, false, 30 , true,true);
                        }

                    }
                });

        /**
         * 打印图片
         */
        findViewById(R.id.btn_printImage).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        // 获取图片
                        Bitmap btMap = BitmapFactory.decodeResource(getResources(),
                                R.drawable.demo);

                        if (paperHeight == 30) {
                            btMap = PrintUtils.zoomImg(btMap, 160, 160);
                        } else {
                            btMap = PrintUtils.zoomImg(btMap, 210, 210);
                        }

                        /**
                         * 打印图片
                         * @param paper_width 纸张宽度选择，目前只有30mm、40mm和52mm可选
                         * @param align  对齐方式，其中0为居左，1为居中，2为居右
                         * @param top 对齐方式，对齐方式，其中0、1为居上，2为居中，3为居下
                         * @param bitmap 需要打印的图片
                         * @param isLabel 是否进行标签走纸，设为true时候打印完自动走纸到下一页，只有开启标签/黑标功能时有效
                         * @param tearPape  打印完是否要撕纸，设为true时候会打印完多走3空行，把纸张推出来，方便撕纸操作,只有关闭标签/黑标功能时有效
                         */
                        PrintUtils.printBitmap(paperWidth,paperAlign,paperTop, btMap, true,true);

                    }
                });

        findViewById(R.id.btn_update).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent mIntent = new Intent(MainActivity.this, UpdateActivity.class);

                startActivity(mIntent);

            }
        });

        /**
         * 打印自检
         */
        findViewById(R.id.btn_printSelf).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        PrintUtils.printTest();
                    }
                });

        /**
         * 扫描
         */
        findViewById(R.id.btn_scan1).setOnClickListener(
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        PrintUtils.openScan();
                    }
                });

        /**
         * 纸张类型选择
         */
        rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                //普通热敏纸
                if (arg1 == R.id.rbtn1) {
                    // 关闭标签检测指令，即关闭黑标功能
                    PrintUtils.labelEnable(false);
                }
                //间隙标签纸
                else {
                    // 打开标签检测指令，即开启黑标功能
                    PrintUtils.labelEnable(true);
                }
            }
        });

        /**
         * 纸张高度类型选择
         */
        paper_height.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                //30间隙纸
                if (arg1 == R.id.paper_30_height) {
                    paperHeight = 30;
                }
                //40间隙纸
                else {
                    paperHeight = 40;
                }
            }
        });

        /**
         * 纸张宽度类型选择
         */
        paper_width.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                //30间隙纸
                if (arg1 == R.id.paper_30_width) {
                    paperWidth = 30;
                }
                //40mm宽
                else if(arg1 == R.id.paper_40_width) {
                    paperWidth = 40;
                }
                //58mm宽
                else if(arg1 == R.id.paper_52_width) {
                    paperWidth = 52;
                }
            }
        });

        /**
         * 文字大小
         */
        paper_text_size.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                //1 normal , NORMAL = {0x1d, 0x21, 0x00}
                if (arg1 == R.id.paper_00_text_size) {
                    paperTextSize = 1;
                }
                //2 lager width , DOUBLE_WIDTH = {0x1d, 0x21, 0x10}
                else if(arg1 == R.id.paper_10_text_size) {
                    paperTextSize = 2;
                }
                //3 lager high , DOUBLE_HEIGHT = {0x1d, 0x21, 0x01};
                else if(arg1 == R.id.paper_01_text_size) {
                    paperTextSize = 3;
                }
                //3 lager width high , DOUBLE_HEIGHT_WIDTH = {0x1d, 0x21, 0x11};
                else if(arg1 == R.id.paper_11_text_size) {
                    paperTextSize = 4;
                }
            }
        });

        /**
         * 左右位置选择
         */
        paper_align.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                //left 0
                if (arg1 == R.id.paper_left_align) {
                    paperAlign = 0;
                }
                //center 1
                else if(arg1 == R.id.paper_center_align) {
                    paperAlign = 1;
                }
                //right 2
                else if(arg1 == R.id.paper_right_align) {
                    paperAlign = 2;
                }
            }
        });

        /**
         * 上下位置选择
         */
        paper_top.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                if (arg1 == R.id.paper_start_top) {
                    paperTop = 0;
                }
                else if(arg1 == R.id.paper_center_top) {
                    paperTop = 1;
                }
                else if(arg1 == R.id.paper_bottom_top) {
                    paperTop = 2;
                }
                else if(arg1 == R.id.paper_bottombottom_top) {
                    paperTop = 3;
                }
            }
        });

        scanBroadcastReceiver = new ScanBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.qs.scancode");
        this.registerReceiver(scanBroadcastReceiver, intentFilter);

        scanBroadcastReceiver1 = new ScanBroadcastReceiver1();
        IntentFilter intentFilter1 = new IntentFilter();
        intentFilter1.addAction("qsapi.intent.key_scan_down");
        registerReceiver(scanBroadcastReceiver1, intentFilter1);

        getMessageBroadcastReceiver = new GetMessageBroadcastReceiver();
        IntentFilter intentFilter_getMessage = new IntentFilter();
        intentFilter_getMessage.addAction("com.qs.getmassage");
        this.registerReceiver(getMessageBroadcastReceiver, intentFilter_getMessage);

        if (textToSpeech == null) {
            textToSpeech = new TextToSpeech(getApplicationContext(), this);
        }

        try {
            showDeviceMessage();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //显示设备信息二维码
    void showDeviceMessage(){

        String sn = get("gsm.cust.serial");
        String imei1 = get("gsm.imei.sim1");
        String imei2 = get("gsm.imei.sim2");

        Bitmap btMap_all = BarcodeCreater.creatBarcode(
                MainActivity.this,
                imei1 + ";"
                        + imei2
                        + ";" +
                        sn
                        +
                        ";"
                        + android.os.Build.MODEL + ";"
                        + Build.DISPLAY + ";"
                        + getVersionName(this) + ";"
                        + getVersionCode(this) , 500, 300,
                true, 2, 15);
        device_img.setImageBitmap(btMap_all);

    }


    @SuppressWarnings("finally")
    public static String get(String key) {
        String value = "";
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class, String.class);
            value = (String) (get.invoke(c, key, "unknown"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return value;
        }
    }

    public static int getVersionCode(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            return -1;
        }
    }

    public static String getVersionName(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "unknown";
        }
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            //初始化tts引擎
            int result = textToSpeech.setLanguage(Locale.CHINA);
            //设置参数
            ttsParam();
            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {

            }
        }
    }

    private void ttsParam() {
        textToSpeech.setPitch(1.4f);// 设置音调，,1.0是常规
        textToSpeech.setSpeechRate(1.8f);//设定语速，1.0正常语速
    }

    // SCAN按键的监听
    class ScanBroadcastReceiver1 extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            findViewById(R.id.btn_scan1).performClick();

        }
    }

    /**
     * 获取扫描信息
     *
     * @author wu
     */
    class ScanBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent1) {
            // TODO Auto-generated method stub
            String text1 = intent1.getExtras().getString("data").trim();
            if (text1.contains("MM")) {
                return;
            }
            if (text1.equals("M")) {
                return;
            }
            if (text1.length() <= 0) {
                return;
            }

            //此广播可以把扫描数据输入到当前焦点编辑框里面
            Intent intent = new Intent("com.eastaeon.android.PRINT_TO_FOCUS");
            intent.putExtra("data", text1 + "\n");
            sendBroadcast(intent);

//            tv.setText(text1);
            //播放提示音
            player.start();
            Toast.makeText(context, "扫描信息：" + text1, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 打印信息接收
     *
     * @author wu
     */
    class GetMessageBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            int message = intent.getIntExtra("message", 0);
            switch (message) {
                case 0:
                    //print success
                    Toast.makeText(context, "打印成功", Toast.LENGTH_SHORT).show();
                    printComplete = true;
                    break;
                case 1:
                    //no paper
                    Toast.makeText(context, "缺纸", Toast.LENGTH_SHORT).show();
                    textToSpeech.speak(getString(R.string.no_paper), TextToSpeech.QUEUE_FLUSH, null);
                    break;
                default:
                    break;
            }
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        unregisterReceiver(getMessageBroadcastReceiver);
        PrintUtils.closeCommonApi();
        System.exit(0);
        super.onBackPressed();
    }

}
